package com.xiaozhengkeji.mcverifyplus.api.user.v1;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import com.xiaozhengkeji.mcverifyplus.base.entitys.SystemUserEntity;
import com.xiaozhengkeji.mcverifyplus.base.service.SystemUserEntityService;
import com.xiaozhengkeji.mcverifyplus.events.user.WebUserLoginEvent;
import com.xiaozhengkeji.mcverifyplus.pojo.ResponseBean;
import com.xiaozhengkeji.mcverifyplus.pojo.type.ResCodeType;
import com.xiaozhengkeji.mcverifyplus.service.BusUserService;
import com.xiaozhengkeji.mcverifyplus.service.EMailService;
import com.xiaozhengkeji.mcverifyplus.utils.AddressesUtil;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;
import wiki.xsx.core.util.RedisUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * 用户Api
 */
@Slf4j
@RestController
@RequestMapping("/web/user")
public class UserApi {
    @Autowired
    SystemUserEntityService systemUserEntityService;
    @Autowired
    EMailService eMailService;
    @Autowired
    BusUserService busUserService;

    @Autowired
    ApplicationContext applicationContext;

    @PostMapping("/register")
    public ResponseBean register(@RequestParam("username") String username,
                                 @RequestParam("mailbox") String mailbox,
                                 @RequestParam("password") String password,
                                 @ApiParam("邮箱验证码") @RequestParam("mailboxcode") String mailboxcode,
                                 HttpServletRequest request) {
        String redis_verificationCode = RedisUtil.getStringHandler(21).get("Register_" + mailbox);
        if (!redis_verificationCode.equalsIgnoreCase(mailboxcode)) {
            return new ResponseBean(ResCodeType.Error, "验证码错误!", null, 1);
        }
        int ret = busUserService.registeredUser(username, mailbox, password, AddressesUtil.getIpAddress(request));
        if (ret == 1) {
            RedisUtil.getStringHandler(21).remove("Register_" + mailbox);
            return new ResponseBean(ResCodeType.Success, "注册成功!", ret, null);
        } else {
            return new ResponseBean(ResCodeType.Error, "注册失败!服务器错误", ret, 2);
        }
    }

    /**
     * 发送注册验证码
     */
    @GetMapping("/register/sendEMail")
    public ResponseBean sendEMail(@RequestParam("username") String username,
                                  @RequestParam("mailbox") String mailbox,
                                  @ApiParam("获取图片验证码时提交的时间戳") @RequestParam("verificationCodeTag") String verificationCodeTag,
                                  @ApiParam("图片验证码的验证码") @RequestParam("verificationCode") String verificationCode) {
        String redis_gcv = RedisUtil.getStringHandler(20).get("GVC_" + verificationCodeTag);
        if (!redis_gcv.equalsIgnoreCase(verificationCode)) {
            return new ResponseBean(ResCodeType.Error, "验证码错误!", null, 2);
        }
        RedisUtil.getStringHandler(20).remove("GVC_" + verificationCodeTag);
        List<SystemUserEntity> systemUser_base = systemUserEntityService.queryByMailBox(mailbox);
        if (systemUser_base.size() > 0) {
            return new ResponseBean(ResCodeType.Error, "邮箱已被注册!", null, 1);
        }
        if (RedisUtil.getStringHandler(21).get("Register_" + mailbox) != null) {
            return new ResponseBean(ResCodeType.Error, "已发送过验证码!", null, 3);
        }
        String emailBox_VerificationCode = RandomUtil.randomString(5).toUpperCase(Locale.ROOT);
        eMailService.sendRegisterEMail(mailbox, username, emailBox_VerificationCode);
        RedisUtil.getStringHandler(21).set("Register_" + mailbox, emailBox_VerificationCode, 60 * 10, TimeUnit.SECONDS);
        return new ResponseBean(ResCodeType.Success, "已发送验证码!请在10分钟内完成注册!", null, null);
    }

    /**
     * 登录账号
     */
    @PostMapping("login")
    public ResponseBean login(@RequestParam("mailbox") String mailbox,
                              @RequestParam("password") String password,
                              @ApiParam("获取图片验证码时提交的时间戳") @RequestParam("verificationCodeTag") String verificationCodeTag,
                              @ApiParam("图片验证码的验证码") @RequestParam("verificationCode") String verificationCode,
                              HttpServletRequest request) {
        String redis_gcv = RedisUtil.getStringHandler(20).get("GVC_" + verificationCodeTag);
        if (!redis_gcv.equalsIgnoreCase(verificationCode)) {
            return new ResponseBean(ResCodeType.Error, "验证码错误!", null, 2);
        }
        RedisUtil.getStringHandler(20).remove("GVC_" + verificationCodeTag);
        List<SystemUserEntity> systemUser_base = systemUserEntityService.queryByMailBoxAndPassWord(mailbox, password);
        if (systemUser_base.size() < 1) {
            applicationContext.publishEvent(new WebUserLoginEvent(null, mailbox, password, AddressesUtil.getIpAddress(request), false));
            return new ResponseBean(ResCodeType.Error, "用户名或密码错误!", null, 1);
        }
        applicationContext.publishEvent(new WebUserLoginEvent(null, mailbox, password, AddressesUtil.getIpAddress(request), true));
        StpUtil.setLoginId(systemUser_base.get(0).getId());
        return new ResponseBean(ResCodeType.Success, "登录成功", StpUtil.getTokenInfo(), StpUtil.getTokenInfo().tokenValue);
    }

    /**
     * 验证Token的有效性
     */
    @GetMapping("verifyToken")
    public ResponseBean verifyToken(@RequestParam("Token") String Token) {
        if (StpUtil.getLoginIdByToken(Token) == null) {
            return new ResponseBean(ResCodeType.Error, "Token过期!", null, null);
        }
        return new ResponseBean(ResCodeType.Success, "自动登录成功!", null, null);
    }
}
